package com.pine.service.pineframework.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysDictItemQueryRequest;
import com.pine.common.beans.pineframework.response.SysDictItemQueryResponse;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.beans.response.PageResponse;
import com.pine.dao.pineframework.entity.SysDictItem;
import com.pine.manager.pineframework.SysDictItemManager;
import com.pine.manager.pineframework.bo.SysDictItemBo;
import com.pine.manager.pineframework.convertors.SysDictItemConvertor;
import com.pine.manager.pineframework.query.SysDictItemQuery;
import com.pine.service.pineframework.SysDictItemService;
import com.pine.service.util.PageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-12
 */
@Slf4j
@Service
public class SysDictItemServiceImpl implements SysDictItemService {

    @Resource
    private SysDictItemManager sysDictItemManager;

    @Resource
    private SysDictItemConvertor sysDictItemConvertor;

    private static final Map<String, SFunction<SysDictItem, ?>> COLUMNS_FUNCTION_MAP;
    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", SysDictItem::getId
        );
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public SysDictItemQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        SysDictItemBo sysDictItemBo = sysDictItemManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, SysDictItem::getId));
        return sysDictItemConvertor.entityBoToQueryResponse(sysDictItemBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<SysDictItemQueryResponse> list(SysDictItemQueryRequest request) {
        SysDictItemQuery sysDictItemQuery = sysDictItemConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(sysDictItemQuery)) {
            List<SysDictItemBo> sysDictItemList = sysDictItemManager.list(sysDictItemQuery);
            if (ObjectUtils.isNotEmpty(sysDictItemList)) {
                return sysDictItemList.stream()
                        .map(sysDictItemConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<SysDictItemQueryResponse> listPages(PageRequest<SysDictItemQueryRequest> request) {
        try {
            // 分页查询
            IPage<SysDictItemBo> sysDictItemPage = sysDictItemManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(sysDictItemPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param sysDictItemPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<SysDictItemQueryResponse> safelyConvertPage(IPage<SysDictItemBo> sysDictItemPage) {
        if (sysDictItemPage == null || sysDictItemPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<SysDictItemQueryResponse> responses = sysDictItemPage.getRecords().parallelStream()
            .map(sysDictItemBo -> sysDictItemConvertor.entityBoToQueryResponse(sysDictItemBo))
            .collect(Collectors.toList());

        return PageUtil.convertPage(sysDictItemPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<SysDictItemQuery> transformToQuery(PageRequest<SysDictItemQueryRequest> request) {
        SysDictItemQuery sysDictItemQuery = sysDictItemConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), sysDictItemQuery);
    }
}
